import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import { replace } from 'core-js/fn/symbol'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist
    //全局路由拦截
router.beforeEach(async(to, from, next) => {
    //进度条开始
    NProgress.start()
        // 设置页头标题
    document.title = getPageTitle(to.meta.title)

    // 获取token
    const hasToken = getToken()
    if (hasToken) {
        if (to.path === '/login') {
            // 如果是登录页直接进入，进度条结束
            next({ path: '/' })
            NProgress.done()
        } else {
            if (!store.getters.role) {
                store.dispatch('user/getInfo').then(res => {
                    const hasGetUserRoles = res[0].role;
                    store.dispatch('permission/GenerateRoutes', { hasGetUserRoles }).then(() => {
                        //生成可访问路由表
                        router.addRoutes(store.getters.addRoutes)
                        next({...to, replace: true }) //hack方法 确保路由已生成 打断原有导航重新导航
                    })
                }).catch(err => {
                    console.log(err);
                })
            } else {
                store.dispatch('basic/getDict').then(res => {
                    next() //当vuex里的roles不再是空，说明可访问路由已生成
                })
            }
        }
    } else {
        /* has no token*/
        // 白名单直接进入
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            // store.dispatch('basic/getDict').then(res => {
            next() //当vuex里的roles不再是空，说明可访问路由已生成
                // })
        } else {
            //不再白名单 全部重定向到登录页 并保存之前的路由
            // other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})